import svc
import entities
import util
import entityCommon
import uthread

class EveEntitySpawnService(svc.entitySpawnClient, entities.EveEntityAppSpawnMixin):
    __guid__ = 'svc.eveEntitySpawnClient'
    __replaceservice__ = 'entitySpawnClient'
    __notifyevents__ = (svc.entitySpawnClient.__notifyevents__ + ['OnSessionChanged'])

    def Run(self, *etc):
        svc.entitySpawnClient.Run(self, etc)
        self.charMgr = sm.RemoteSvc('charMgr')
        self.paperDollServer = sm.RemoteSvc('paperDollServer')



    def AppSpawn(self, generator):
        return entities.EveEntityAppSpawnMixin.AppSpawn(self, generator)



    def _ChooseSpawnLocation(self, worldspaceID):
        logonCount = sm.RemoteSvc('charMgr').GetPrivateInfo(session.charid).logonCount
        if (logonCount == 0):
            worldSpaceTypeID = sm.GetService('worldSpaceClient').GetWorldSpaceTypeIDFromWorldSpaceID(worldspaceID)
            worldSpaceLocatorRowSet = cfg.worldspaceLocators.get(worldSpaceTypeID)
            if worldSpaceLocatorRowSet:
                locator = worldSpaceLocatorRowSet[0]
                spawnPoint = (locator.posX,
                 locator.posY,
                 locator.posZ)
                spawnRot = (locator.yaw,
                 locator.pitch,
                 locator.roll)
                return (spawnPoint, spawnRot)
            (spawnPoint, spawnRot,) = sm.GetService('worldSpaceClient').GetWorldSpaceSafeSpot(session.worldspaceid)
            return (spawnPoint, spawnRot)



    def SpawnClientSidePlayer(self):
        scene = self.entityService.LoadEntitySceneAndBlock(session.stationid)
        playerTypeID = cfg.eveowners.Get(session.charid).Type().id
        serverInfoCalls = []
        serverInfoCalls.append((self.paperDollServer.GetPaperDollData, (session.charid)))
        serverInfoCalls.append((self.charMgr.GetPublicInfo, (session.charid)))
        (paperdolldna, pubInfo,) = uthread.parallel(serverInfoCalls)
        recipeSvc = sm.GetService('entityRecipeSvc')
        overrides = {}
        (spawnPoint, spawnRot,) = self._ChooseSpawnLocation(session.worldspaceid)
        self.OverridePosition(overrides, spawnPoint, spawnRot)
        paperDollComponentID = const.zentity.PAPER_DOLL_COMPONENT_ID
        overrides[paperDollComponentID] = {'gender': pubInfo.gender,
         'dna': paperdolldna,
         'typeID': playerTypeID}
        recipe = recipeSvc.GetTypeRecipe(playerTypeID, overrides)
        spawnedEntity = self.entityService.CreateEntityFromRecipe(scene, recipe, session.charid)
        scene.CreateAndRegisterEntity(spawnedEntity)



    def OnSessionChanged(self, isRemote, session, change):
        if not util.IncarnaNPEEnabled():
            return 
        (oldws, newws,) = change.get('worldspaceid', (None, None))
        if (newws and self.entityService.IsClientSideOnly(newws)):
            self.SpawnClientSidePlayer()




